package com.yhhvip.lottery.service.impl;

import com.yhhvip.lottery.dao.mybatis.mapper.LotSysResourcesMapper;
import com.yhhvip.lottery.dao.mybatis.model.LotSysResources;
import com.yhhvip.lottery.domain.ReqLotSysResources;
import com.yhhvip.lottery.domain.res.ResLotSysResources;
import com.yhhvip.lottery.service.LotSysResourcesService;
import org.springframework.beans.BeanUtils;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author XOu
 * @description 资源业务处理层
 * @date 2018/6/25
 */
@Service("resourcesService")
public class LotSysResourcesServiceImpl implements LotSysResourcesService {
    @Resource
    private LotSysResourcesMapper resourcesMapper;

    @Override
    public List<ResLotSysResources> queryAll() {
        return resourcesMapper.queryAll();
    }

    @Override
    @Cacheable(cacheNames = "resources", key = "#map['userid'].toString()+#map['type']")
    public List<ResLotSysResources> loadUserResources(Map<String, Object> map) {
        List<ResLotSysResources> list = resourcesMapper.loadUserResources(map);
        for (ResLotSysResources resources : list) {
            map.put("parentId", resources.getId());
            getResourcesTree(resources);
        }
        return list;
    }

    /**
     * @param resource
     * @Title: getResourcesTree
     * @Description: 获取权限树
     * @return: void
     */
    public void getResourcesTree(ResLotSysResources resource) {
        Map<String, Object> map = new HashMap<>();
        map.put("parentId", resource.getId());
        List<ResLotSysResources> list = queryResourcesByParentId(map);
        if (!list.isEmpty()) {
            resource.setResourceGroup(list);
            for (ResLotSysResources seedResources : list) {
                getResourcesTree(seedResources);
            }
        }
        return;
    }

    @Override
    public List<ResLotSysResources> queryResourcesListWithSelected(Long rid) {
        return resourcesMapper.queryResourcesListWithSelected(rid);
    }

    @Override
    public void save(ReqLotSysResources resources) {
        LotSysResources lotSysResources = new LotSysResources();
        BeanUtils.copyProperties(resources, lotSysResources);
        resourcesMapper.insertSelective(lotSysResources);
    }

    @Override
    public void delete(Long id) {
        resourcesMapper.deleteByPrimaryKey(id);
    }

    @Override
    public List<ResLotSysResources> queryResourcesByParentId(Map<String, Object> map) {
        return resourcesMapper.queryResourcesByParentId(map);
    }
}
